package com.starsky.common.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 *@desc: 生成id工具
 *@author: wangsh
 *
 */
public class UUIDUtils {
    /**
     * 产生一个32位的GUID
     *
     * @return
     */
    public static String newGUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    /**
     * 获取32位GUID
     *
     * @return
     */
    public static String getId() {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            UUID uuid = UUID.randomUUID();
            String guidStr = uuid.toString();
            md.update(guidStr.getBytes(), 0, guidStr.length());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    /**
     * 生成主键(19位数字)
     * 主键生成方式,年月日时分秒毫秒的时间戳+四位随机数保证不重复
     */
    public static Long getNumId() {
        //当前系统时间戳精确到毫秒
        Long simple = System.currentTimeMillis();
        //三位随机数
        int random = new Random().nextInt(900000) + 100000;//为变量赋随机值100000-99999;
        return Long.decode((simple.toString() + random));
    }

    /**
     * 获取移除横线并转大写的UUID
     */
    public static final String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }

    /**
     * 时间+随机数=流水号
     *
     * @return
     */
    public static String getSerial(String pre, Integer len) {
        Random rm = new Random();
        Integer pross = (int) ((1 + rm.nextDouble()) * Math.pow(10, len));
        String rand = String.valueOf(pross).substring(1, len + 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = dateFormat.format(new Date());
        return pre.toUpperCase() + date + rand;
    }

    /**
     * 时间戳+随机数=流水号
     */
    public static String getSerialSjc(String pre, Integer len) {
        Random rm = new Random();
        Integer pross = (int) ((1 + rm.nextDouble()) * Math.pow(10, len));
        String rand = String.valueOf(pross).substring(1, len + 1);
        return pre.toUpperCase() + System.currentTimeMillis() + rand;
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(getId());
    }
}
